package com.ssy.lingxi.order.serviceimpl.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.FundModeEnum;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.constant.marketing.BelongTypeEnum;
import com.ssy.lingxi.common.constant.order.OrderModeEnum;
import com.ssy.lingxi.common.constant.order.OrderTradeProcessTypeEnum;
import com.ssy.lingxi.common.constant.order.OrderTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.order.entity.*;
import com.ssy.lingxi.order.model.bo.*;
import com.ssy.lingxi.order.model.constant.*;
import com.ssy.lingxi.order.model.dto.OrderInvoiceDTO;
import com.ssy.lingxi.order.model.dto.SupplyProductDTO;
import com.ssy.lingxi.order.model.vo.basic.request.*;
import com.ssy.lingxi.order.model.vo.basic.response.*;
import com.ssy.lingxi.order.model.vo.buyer.response.BuyerOrderPayNodeDetailVO;
import com.ssy.lingxi.order.model.vo.vendor.request.*;
import com.ssy.lingxi.order.model.vo.vendor.response.*;
import com.ssy.lingxi.order.repository.*;
import com.ssy.lingxi.order.service.base.*;
import com.ssy.lingxi.order.service.web.IDeliveryPlanService;
import com.ssy.lingxi.order.service.web.IOrderCreationService;
import com.ssy.lingxi.order.service.web.IVendorOrderService;
import com.ssy.lingxi.order.utils.NumberUtil;
import org.apache.poi.ss.usermodel.CellStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 销售订单相关接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-07-20
 */
@Service
public class VendorOrderServiceImpl implements IVendorOrderService {

    private final static Logger logger = LoggerFactory.getLogger(VendorOrderServiceImpl.class);

    @Resource
    private IBaseCacheService baseCacheService;

    @Resource
    private IBaseOrderService baseOrderService;

    @Resource
    private IBaseOrderProcessService baseOrderProcessService;

    @Resource
    private IBaseOrderTaskService baseOrderTaskService;

    @Resource
    private IBaseOrderProductService baseOrderProductService;

    @Resource
    private IBaseOrderInvoiceService baseOrderInvoiceService;

    @Resource
    private IBaseOrderPaymentService baseOrderPaymentService;

    @Resource
    private IBaseOrderDeliveryService baseOrderDeliveryService;

    @Resource
    private IBaseOrderPromotionService baseOrderPromotionService;

    @Resource
    private IBaseOrderCouponService baseOrderCouponService;

    @Resource
    private IBaseOrderHistoryService baseOrderHistoryService;

    @Resource
    private IOrderCreationService orderCreationService;

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderProductRepository orderProductRepository;

    @Resource
    private IBaseOrderScheduleService baseOrderScheduleService;

    @Resource
    private IBaseOrderConsigneeService baseOrderConsigneeService;

    @Resource
    private SellDeliveryGoodsRepository sellDeliveryGoodsRepository;

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    @Resource
    private OrderDeliveryRepository orderDeliveryRepository;

    @Resource
    private IBaseOrderDeductionService baseOrderDeductionService;

    @Resource
    private IDeliveryPlanService deliveryPlanService;

    @Resource
    private OrderPromotionRepository orderPromotionRepository;

    /**
     * （待分配订单页面） 获取前端页面下拉框列表
     *
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<DropdownItem>> getTakePageItems(HttpHeaders headers) {
        return Wrapper.success(baseOrderService.listOrderTypes());
    }

    /**
     * “待分配订单” - 查询订单列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<BaseVendorOrderQueryVO>> pageToTakeOrders(HttpHeaders headers, OrderPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Page<OrderDO> pageList = baseOrderService.pageVendorToTakeOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getStoreIds(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            BaseVendorOrderQueryVO queryVO = new BaseVendorOrderQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setBuyerMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setDeliverAddress(baseOrderConsigneeService.orderConsigneeToString(order.getConsignee()));
            queryVO.setRelationNo(StringUtils.hasLength(order.getRelationNo()) ? order.getRelationNo() : "");
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待分配订单” - 订单详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorOrderDetailVO> getToTakeOrderDetail(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return baseOrderService.getVendorOrderDetail(order);
    }

    /**
     * “待分配订单” - 领取订单
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> takeOrder(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if(order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //判断是否已经被领取
        if(!baseOrderService.canVendorTakeOrder(order)) {
            return Wrapper.fail(ResponseCode.ORDER_HAS_BEEN_TAKEN);
        }

        order.setVendorUserId(loginUser.getUserId());
        orderRepository.saveAndFlush(order);
        return Wrapper.success();
    }

    /**
     * “待分配订单” - 批量领取订单
     *
     * @param headers  Http头部信息
     * @param orderIds 订单Id列表
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> batchTakeOrders(HttpHeaders headers, List<OrderIdVO> orderIds) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        if(CollectionUtils.isEmpty(orderIds)) {
            return Wrapper.success();
        }

        List<OrderDO> orders = orderRepository.findAllById(orderIds.stream().map(OrderIdVO::getOrderId).collect(Collectors.toList()));
        if(orders.size() != orderIds.size() || orders.stream().anyMatch(order -> !order.getVendorMemberId().equals(loginUser.getMemberId()) && !order.getVendorRoleId().equals(loginUser.getMemberRoleId()))) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        if(orders.stream().anyMatch(order -> !baseOrderService.canVendorTakeOrder(order))) {
            return Wrapper.fail(ResponseCode.ORDER_HAS_BEEN_TAKEN);
        }

        orders.forEach(order -> order.setVendorUserId(loginUser.getUserId()));
        orderRepository.saveAll(orders);
        return Wrapper.success();
    }

    /**
     * "待核销自提订单" - 分页查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorVerifyOrderQueryVO>> pageVerifyOrders(HttpHeaders headers, VendorVerifyOrderPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Page<OrderDO> pageList = baseOrderService.pageVendorPickUpOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), VendorInnerStatusEnum.VENDOR_DELIVERY_CONFIRMED.getCode(), OrderOuterStatusEnum.TO_RECEIPT.getCode(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            VendorVerifyOrderQueryVO queryVO = new VendorVerifyOrderQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setBuyerMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setDeliverAddress(baseOrderConsigneeService.orderConsigneeToString(order.getConsignee()));
            queryVO.setRelationNo(StringUtils.hasLength(order.getRelationNo()) ? order.getRelationNo() : "");
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * "待核销自提订单" - 核销自提订单
     * @param headers Http头部信息
     * @param orderVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> validateVerifyOrder(HttpHeaders headers, VendorVerifyOrderVO orderVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);

        OrderDeliveryDO orderDeliveryDO = orderDeliveryRepository.findFirstByOrderIdAndBatchNo(orderVO.getOrderId(), orderVO.getBatchNo());
        if (orderDeliveryDO == null) {
            return Wrapper.fail(ResponseCode.ORDER_DELIVERY_DOES_NOT_EXIST);
        }

        //自提码校验
        if (!orderDeliveryDO.getSelfCode().equals(orderVO.getSelfCode())) {
            return Wrapper.fail(ResponseCode.ORDER_SELF_CODE_MISMATCHED);
        }

        //更新供应商内部状态为“自提订单已核销”
        orderDeliveryDO.setVendorInnerStatus(VendorInnerStatusEnum.VENDOR_TO_SELF_ORDER_VERIFY.getCode());

        orderDeliveryRepository.saveAndFlush(orderDeliveryDO);
        return Wrapper.success();
    }

    /**
     * 获取前端页面下拉框列表
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<PageItemVO> getPageItems(HttpHeaders headers) {
        baseCacheService.needLoginFromBusinessPlatform(headers);
        PageItemVO itemVO = new PageItemVO();
        itemVO.setInnerStatus(VendorInnerStatusEnum.toDropdownList());
        itemVO.setOuterStatus(OrderOuterStatusEnum.toDropdownList());
        itemVO.setOrderTypes(baseOrderService.listOrderTypes());
        return Wrapper.success(itemVO);
    }

    /**
     * 分页查询订单
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorOrderQueryVO>> pageOrders(HttpHeaders headers, OrderManagePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Page<OrderDO> pageList = baseOrderService.pageVendorOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), pageVO.getInnerStatus(), pageVO.getOuterStatus(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            VendorOrderQueryVO queryVO = new VendorOrderQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setBuyerMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setDeliverAddress(baseOrderConsigneeService.orderConsigneeToString(order.getConsignee()));
            queryVO.setRelationNo(StringUtils.hasLength(order.getRelationNo()) ? order.getRelationNo() : "");
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            queryVO.setBuyerMemberId(order.getBuyerMemberId());
            queryVO.setBuyerRoleId(order.getBuyerRoleId());
            queryVO.setShopId(order.getShopId());
            queryVO.setShopType(order.getShopType());
            queryVO.setShopEnvironment(order.getShopEnvironment());
            //按钮显示
            queryVO.setShowCancel(baseOrderService.canVendorCancelOrder(order));
            queryVO.setShowTerminate(baseOrderService.canTerminateOrder(order));
            queryVO.setShowComment(baseOrderService.canVendorCommentOrder(order));
            queryVO.setShowTransfer(baseOrderService.canTransferOrder(order));
            queryVO.setShowModifyPrice(baseOrderService.canVendorModifyOrderPrice(order));
            queryVO.setShowGeneratePayLink(baseOrderService.canVendorGeneratePayLink(order));
            queryVO.setShowModifyOrder(baseOrderService.canVendorModifyOrder(order));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * @param token    登录token
     * @param pageVO   接口参数
     * @param response 响应体
     */
    @Override
    public void exportOrders(HttpServletResponse response, OrderManagePageVO pageVO, String token) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(token);

        //获取销售订单导出数据
        List<OrderDO> orderList = baseOrderService.exportVendorOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), pageVO.getInnerStatus() == null ? null : Collections.singletonList(pageVO.getInnerStatus()), pageVO.getOuterStatus());

        List<Map<String, Object>> rows = orderList.stream().map(order -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("订单编号", order.getOrderNo());
            map.put("订单摘要", order.getDigest());
            map.put("采购会员名称", order.getBuyerMemberName());
            map.put("下单时间", order.getCreateTime());
            map.put("订单总额", NumberUtil.formatAmount(order.getTotalAmount()));
            map.put("订单类型名称", OrderTypeEnum.getNameByCode(order.getOrderType()));
            map.put("转单订单号", StrUtil.isEmpty(order.getRelationNo()) ? "" : order.getRelationNo());
            map.put("外部状态名称", OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            map.put("内部状态名称", VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            return map;
        }).collect(Collectors.toList());


        ExcelWriter writer = ExcelUtil.getBigWriter();
        CellStyle style = writer.getHeadCellStyle();
        style.setWrapText(true);
        writer.write(rows);

        String fileName = "销售订单-" + DateUtil.date() + ".xls";
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    /**
     * 订单详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorOrderDetailVO> getOrderDetail(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }
        if (!order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_WRONG_ROLE);
        }

        return baseOrderService.getVendorOrderDetail(order);
    }

    /**
     * 查询订单优惠券记录
     * @param headers   Http头部信息
     * @param orderIdVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<VendorOrderCouponVO>> findOrderCoupons(HttpHeaders headers, OrderIdVO orderIdVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(orderIdVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return baseOrderCouponService.findOrderCoupons(order);
    }

    /**
     * 查询订单商品的营销活动记录
     * @param headers     Http头部信息
     * @param productIdVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorOrderProductPromotionVO>> findOrderProductPromotions(HttpHeaders headers, OrderProductIdVO productIdVO) {
        baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderProductDO orderProduct = orderProductRepository.findById(productIdVO.getOrderProductId()).orElse(null);
        if (orderProduct == null) {
            return Wrapper.fail(ResponseCode.ORDER_PRODUCT_DOES_NOT_EXIST);
        }
        Pageable page = PageRequest.of(productIdVO.getCurrent() - 1, productIdVO.getPageSize(), Sort.by("id").descending());
        Page<OrderPromotionDO> promotionPage = orderPromotionRepository.findAllByProduct(orderProduct, page);

        List<VendorOrderProductPromotionVO> promotionList = promotionPage.getContent().stream().map(promotion -> {
            VendorOrderProductPromotionVO promotionVO = new VendorOrderProductPromotionVO();
            promotionVO.setPromotionId(promotion.getPromotionId());
            promotionVO.setName(promotion.getName());
            promotionVO.setPromotionType(promotion.getPromotionType());
            promotionVO.setPromotionTypeName(ActivityTypeEnum.getMessage(promotion.getPromotionType()));
            promotionVO.setBelongType(promotion.getBelongType());
            promotionVO.setBelongTypeName(BelongTypeEnum.getCodeMessage(promotion.getBelongType()));
            promotionVO.setStartTime(promotion.getStartTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            promotionVO.setExpireTime(promotion.getExpireTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            return promotionVO;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(promotionPage.getTotalElements(), promotionList));
    }

    /**
     * 中止订单
     * @param headers  Http头部信息
     * @param reasonVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> terminateOrder(HttpHeaders headers, OrderReasonVO reasonVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(reasonVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //判断中止条件
        if (!baseOrderService.canTerminateOrder(order)) {
            return Wrapper.fail(ResponseCode.ORDER_CAN_NOT_BE_TERMINATED);
        }

        //将订单未发货的数量返回库存，SRM订单、请购采购订单不需要返还库存
        Wrapper<Void> resumeResult = baseOrderService.resumeInventory(order);
        if (resumeResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return resumeResult;
        }

        //向合同服务发送消息，取消订单数据
        baseOrderService.cancelSrmOrder(order);

        order.setBuyerInnerStatus(BuyerInnerStatusEnum.TERMINATED.getCode());
        order.setVendorInnerStatus(VendorInnerStatusEnum.TERMINATED.getCode());
        order.setOuterStatus(OrderOuterStatusEnum.TERMINATED.getCode());
        orderRepository.saveAndFlush(order);

        //内部、外部记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.TERMINATE, order.getVendorInnerStatus(), reasonVO.getReason().trim());
        baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), OrderOperationEnum.TERMINATE, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), reasonVO.getReason().trim());

        //Step 4: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());

        //中止订单维护送货计划物料数据
        try{
            deliveryPlanService.removeDeliveryPlanProduct(order);
        }catch (Exception e){
            logger.error("送货计划 - 中止，取消订单时删除送货计划物料数据（内部接口）失败");
        }

        return Wrapper.success();
    }

    /**
     * 取消订单
     * @param headers  Http头部信息
     * @param reasonVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> cancelOrder(HttpHeaders headers, OrderReasonVO reasonVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(reasonVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return cancelOrder(order, loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), loginUser.getMemberRoleName(), reasonVO.getReason());
    }

    /**
     * 取消订单
     *
     * @param orderId          订单Id
     * @param userName         用户名
     * @param organizationName 组织机构名称
     * @param jobTitle         职位
     * @param roleName         角色名称
     * @param reason           取消原因
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> cancelOrder(Long orderId, String userName, String organizationName, String jobTitle, String roleName, String reason) {
        OrderDO order = orderRepository.findById(orderId).orElse(null);
        if (order == null) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return cancelOrder(order, userName, organizationName, jobTitle, roleName, reason);
    }

    /**
     * 取消订单
     *
     * @param order            订单
     * @param userName         用户名
     * @param organizationName 组织机构名称
     * @param jobTitle         职位
     * @param roleName         角色名称
     * @param reason           取消原因
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> cancelOrder(OrderDO order, String userName, String organizationName, String jobTitle, String roleName, String reason) {
        //判断取消条件
        if (!baseOrderService.canVendorCancelOrder(order)) {
            return Wrapper.fail(ResponseCode.ORDER_CAN_NOT_BE_CANCEL);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //将订单未发货的数量返回库存，SRM订单、请购采购订单不需要返回库存
        Wrapper<Void> resumeResult = baseOrderService.resumeInventory(order);
        if (resumeResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return resumeResult;
        }

        //返还已抵扣的积分
        Wrapper<Void> deductionResult = baseOrderDeductionService.returnDeductionPoints(order);
        if (deductionResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(ResponseCode.ORDER_POINTS_RETURN_FAIL);
        }

        //向合同服务发送消息，取消订单数据
        baseOrderService.cancelSrmOrder(order);

        //通知营销服务，返还营销活动、优惠券记录
        baseOrderService.resumePromotions(order);

        order.setBuyerInnerStatus(BuyerInnerStatusEnum.CANCELLED.getCode());
        order.setVendorInnerStatus(VendorInnerStatusEnum.CANCELLED.getCode());
        order.setOuterStatus(OrderOuterStatusEnum.CANCELLED.getCode());
        orderRepository.saveAndFlush(order);

        //Step 4: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());

        //内部、外部记录
        baseOrderHistoryService.saveVendorInnerHistory(order.getVendorMemberId(), order.getVendorRoleId(), userName, organizationName, jobTitle, order.getId(), order.getOrderNo(), OrderOperationEnum.CANCEL, order.getVendorInnerStatus(), reason);
        baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), roleName, OrderOperationEnum.CANCEL, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), reason);

        //取消订单维护送货计划物料数据
        try{
            deliveryPlanService.removeDeliveryPlanProduct(order);
        }catch (Exception e){
            logger.error("送货计划 - 中止，取消订单时删除送货计划物料数据（内部接口）失败");
        }
        return Wrapper.success();
    }

    /**
     * “转单” - 预览转单订单列表
     * @param headers         Http头部信息
     * @param transferOrderVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<VendorTransferOrderQueryVO>> preTransferOrders(HttpHeaders headers, VendorTransferOrderVO transferOrderVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        List<OrderDO> orders = orderRepository.findAllById(transferOrderVO.getOrderIds());
        if (CollectionUtils.isEmpty(orders) || orders.stream().anyMatch(order -> !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId()))) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1:判断转单条件
        if (orders.stream().anyMatch(order -> !baseOrderService.canTransferOrder(order))) {
            return Wrapper.fail(ResponseCode.ORDER_CAN_NOT_TRANSFER);
        }

        //Step 2: 查询上游供应商商品
        List<OrderProductDO> orderProducts = baseOrderProductService.findByOrderIn(orders);
        if (CollectionUtils.isEmpty(orderProducts)) {
            return Wrapper.fail(ResponseCode.ORDER_PRODUCT_DOES_NOT_EXIST);
        }

        Wrapper<List<SupplyProductDTO>> supplyProductResult = baseOrderProductService.findSupplyProducts(transferOrderVO.getRoleId(), orders, orderProducts);
        if (supplyProductResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(supplyProductResult.getCode(), supplyProductResult.getMessage());
        }

        //Step 3: 查询转单前订单的供应商，有没有设置发票信息
        Wrapper<Map<Long, OrderInvoiceDTO>> invoiceResult = baseOrderInvoiceService.findSupplyOrderInvoice(orders);
        if (invoiceResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(invoiceResult.getCode(), invoiceResult.getMessage());
        }

        //Step 4: 查询上游供应商交易流程规则配置
        List<OrderShopProductBO> shopProducts = orders.stream().map(order ->
                new OrderShopProductBO(order, orderProducts.stream().filter(orderProduct -> orderProduct.getOrder().getId().equals(order.getId())).collect(Collectors.toList()), supplyProductResult.getData())
        ).collect(Collectors.toList());
        Wrapper<Map<Long, OrderTradeProcessBO>> processResult = baseOrderProcessService.findVendorTradeProcess(shopProducts);
        if (processResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(processResult.getCode(), processResult.getMessage());
        }

        //Step 5: 查询上游供应商支付方式与支付渠道配置
        Wrapper<Map<VendorBO, List<OrderPayTypeDetailVO>>> payTypeResult = baseOrderProcessService.checkMemberPayments(orders.stream().map(order -> new VendorBO(order.getSupplyMemberId(), order.getSupplyRoleId())).collect(Collectors.toList()));
        if (payTypeResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(payTypeResult.getCode(), payTypeResult.getMessage());
        }

        return Wrapper.success(orders.stream().map(order -> {
            VendorTransferOrderQueryVO queryVO = new VendorTransferOrderQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setDigest(order.getDigest());
            queryVO.setSupplyMemberName(order.getSupplyMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(supplyProductResult.getData().stream().filter(supplyProduct -> supplyProduct.getSupplyMemberId().equals(order.getSupplyMemberId()) && supplyProduct.getSupplyRoleId().equals(order.getSupplyRoleId())).map(supplyProduct -> supplyProduct.getQuantity().multiply(supplyProduct.getPrice())).reduce(BigDecimal.ZERO, BigDecimal::add)));
            return queryVO;
        }).collect(Collectors.toList()));
    }

    /**
     * “转单” - 确认转单
     * @param headers         Http头部信息
     * @param transferOrderVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> transferOrders(HttpHeaders headers, VendorTransferOrderVO transferOrderVO) {
        return orderCreationService.transferOrders(headers, transferOrderVO);
    }

    /**
     * 生成支付链接
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<GeneratePayLinkVO> generatePayLink(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }
        return Wrapper.success(new GeneratePayLinkVO(order));
    }

    /**
     * （订单审核各个页面）获取前端页面下拉框列表
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<ValidatePageItemVO> getValidatePageItems(HttpHeaders headers) {
        baseCacheService.needLoginFromBusinessPlatform(headers);
        ValidatePageItemVO itemVO = new ValidatePageItemVO();
        itemVO.setOrderTypes(baseOrderService.listOrderTypes());
        return Wrapper.success(itemVO);
    }

    /**
     * “待提交审核订单” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<OrderPageQueryVO>> pageSubmitToConfirmOrders(HttpHeaders headers, OrderValidatePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Page<OrderDO> pageList = baseOrderService.pageVendorOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            OrderPageQueryVO queryVO = new OrderPageQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待提交审核订单” - 查询订单详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorOrderDetailVO> getSubmitToConfirmOrderDetails(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return baseOrderService.getVendorOrderDetail(order, Collections.singletonList(VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE));
    }

    /**
     * “分页查询订单列表、待提交审核订单” - 修改运费和商品价格
     * @param headers   Http头部信息
     * @param freightVO 接口参数
     * @return 查询结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> updateFreightAndProductPrices(HttpHeaders headers, VendorUpdateFreightVO freightVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(freightVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

//        //Step 1: 判断条件
//        //只有“待提交审核订单”，才能修改运费与到手价
//        if (!order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode())) {
//            return Wrapper.fail(ResponseCode.ORDER_STATUS_IS_NOT_MATCHED);
//        }

        //如果已经支付过，不能修改
        if (order.getHasPaid()) {
            return Wrapper.fail(ResponseCode.ORDER_CAN_NOT_UPDATE_FREIGHT_WHEN_HAS_PAID);
        }

        //Step 2: 修改订单商品到手价、金额
        if (!CollectionUtils.isEmpty(freightVO.getPrices())) {
            Wrapper<UpdateOrderProductPriceBO> productUpdateResult = baseOrderProductService.vendorUpdateProductPrices(order, freightVO.getPrices());
            if (productUpdateResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Wrapper.fail(productUpdateResult.getCode(), productUpdateResult.getMessage());
            }
            //保存修改商品单价外部订单流转记录
            productUpdateResult.getData().getRemarks().forEach(remark -> baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), OrderOperationEnum.MODIFY_UINT_PRICE, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), remark));

            order.setProductAmount(productUpdateResult.getData().getTotalAmount());
        }

        //Step 3: 修改运费
        if (NumberUtil.notNullAndPositiveZero(freightVO.getFreight())) {
            //修改前运费+修改后运费+修改原因
            String remark = StrFormatter.format(OrderStringEnum.REMARK_FORMAT1.getName(), NumberUtil.formatAmount(order.getFreight()),NumberUtil.formatAmount(freightVO.getFreight()), freightVO.getReason());
            //保存修改运费外部订单流转记录
            baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), OrderOperationEnum.MODIFY_FREIGHT, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), remark);

            order.setFreight(freightVO.getFreight());
        }

        //Step 4: 修改订单总额
        order.setTotalAmount(order.getProductAmount().add(order.getFreight()).subtract(order.getPromotionAmount()).subtract(order.getCouponAmount()).subtract(order.getDeductionAmount()).setScale(2, RoundingMode.HALF_UP));

        //Step 5: 修改支付记录中的支付金额
        Wrapper<Void> paymentUpdateResult = baseOrderPaymentService.vendorUpdatePaymentRate(order);
        if (paymentUpdateResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Wrapper.fail(paymentUpdateResult.getCode(), paymentUpdateResult.getMessage());
        }

        orderRepository.saveAndFlush(order);
        return Wrapper.success();
    }

    /**
     * “待提交审核订单” - 修改支付比例
     * @param headers   Http头部信息
     * @param payRateVO 接口参数
     * @return 查询结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> updatePayRate(HttpHeaders headers, VendorUpdatePayRateVO payRateVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(payRateVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 判断条件
        //只有“待提交审核订单”，才能修改运费与到手价
        if (!order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode())) {
            Wrapper.fail(ResponseCode.ORDER_STATUS_IS_NOT_MATCHED);
        }

        //如果已经支付过，不能修改
        if (order.getHasPaid()) {
            return Wrapper.fail(ResponseCode.ORDER_CAN_NOT_UPDATE_PAY_RATE_WHEN_HAS_PAID);
        }

        //Step 2: 修改支付比例设置
        List<PayNodeBO> payNodes = payRateVO.getPayRates().stream().map(p -> new PayNodeBO(0, p.getBatchNo(), "", p.getPayRate().divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP))).collect(Collectors.toList());
        return baseOrderPaymentService.vendorUpdatePaymentRate(order, payNodes);
    }

    /**
     * “待提交审核订单” - 提交审核
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> submitToConfirmOrder(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(agreeVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_SUBMIT_VALIDATE.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 参数判断
        if (agreeVO.getAgree().equals(OrderServiceContants.DISAGREE) && !StringUtils.hasLength(agreeVO.getReason())) {
            return Wrapper.fail(ResponseCode.ORDER_VALIDATE_REASON_CAN_NOT_BE_EMPTY);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, agreeVO.getAgree());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        //Step 3: 如果是拼团订单，向营销服务发送拼团数据，等待拼团结果通知
        baseOrderService.notifyGroupOrder(order);

        //Step 3-2: 如果是代发货订单,向营销服务发送优惠券信息
        baseOrderService.sendCoupons(order);

        orderRepository.saveAndFlush(order);

        //Step 4: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());

        //Step 5: 向消息服务发送供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(),order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 6: 订单内部流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.SUBMIT_VALIDATE, order.getVendorInnerStatus(), StringUtils.hasLength(agreeVO.getReason()) ? agreeVO.getReason() : "");

        return Wrapper.success();
    }

    /**
     * “待审核订单（一级）” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<OrderPageQueryVO>> pageToValidateGradeOneOrders(HttpHeaders headers, OrderValidatePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Page<OrderDO> pageList = baseOrderService.pageVendorOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE.getCode(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            OrderPageQueryVO queryVO = new OrderPageQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待审核订单（一级）” - 查询订单详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorOrderDetailVO> getToValidateGradeOneOrderDetails(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return baseOrderService.getVendorOrderDetail(order, Collections.singletonList(VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE));
    }

    /**
     * “待审核订单（一级）” - 提交审核
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> validateOrderGradeOne(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(agreeVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 参数判断
        if (agreeVO.getAgree().equals(OrderServiceContants.DISAGREE) && !StringUtils.hasLength(agreeVO.getReason())) {
            return Wrapper.fail(ResponseCode.ORDER_VALIDATE_REASON_CAN_NOT_BE_EMPTY);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, agreeVO.getAgree());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        orderRepository.saveAndFlush(order);

        //Step 3: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());

        //Step 4: 向消息服务发送供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(),order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 5: 订单内部流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.VALIDATE_GRADE_ONE, order.getVendorInnerStatus(), StringUtils.hasLength(agreeVO.getReason()) ? agreeVO.getReason() : "");

        return Wrapper.success();
    }

    /**
     * “待审核订单（一级）” - 批量审核
     * @param headers  Http头部信息
     * @param orderIds 接口参数
     * @return 审核结果
     */
    @Override
    public Wrapper<Void> batchValidateOrdersGradeOne(HttpHeaders headers, List<OrderIdVO> orderIds) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        List<OrderDO> orders = orderRepository.findAllById(orderIds.stream().map(OrderIdVO::getOrderId).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(orders) || orderIds.size() != orders.size() || orders.stream().anyMatch(order -> !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId()))) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 记录每个订单的上一次内部状态，用于发送报表数据
        Map<Long, Integer> lastVendorInnerStatusMap = orders.stream().collect(Collectors.toMap(OrderDO::getId, OrderDO::getVendorInnerStatus));

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        for (OrderDO order : orders) {
            Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, OrderServiceContants.AGREE);
            if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
            }
        }

        orderRepository.saveAll(orders);

        orders.forEach(order -> {
            //Step 3: 向报表服务发送统计数据
            baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatusMap.getOrDefault(order.getId(), 0), order.getVendorInnerStatus());

            //Step 4: 向消息服务发送供应购商实时消息
            baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(),order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());

            //Step 5: 订单内、外流转记录
            baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.VALIDATE_GRADE_ONE, order.getVendorInnerStatus(), "");
        });

        return Wrapper.success();
    }

    /**
     * “待审核订单（二级）” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<OrderPageQueryVO>> pageToValidateGradeTwoOrders(HttpHeaders headers, OrderValidatePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Page<OrderDO> pageList = baseOrderService.pageVendorOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO.getCode(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            OrderPageQueryVO queryVO = new OrderPageQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待审核订单（二级）” - 查询订单详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorOrderDetailVO> getToValidateGradeTwoOrderDetails(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return baseOrderService.getVendorOrderDetail(order, Collections.singletonList(VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO));
    }

    /**
     * “待审核订单（二级）” - 提交审核
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> validateOrderGradeTwo(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(agreeVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 参数判断
        if (agreeVO.getAgree().equals(OrderServiceContants.DISAGREE) && !StringUtils.hasLength(agreeVO.getReason())) {
            return Wrapper.fail(ResponseCode.ORDER_VALIDATE_REASON_CAN_NOT_BE_EMPTY);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, agreeVO.getAgree());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        orderRepository.saveAndFlush(order);

        //Step 3: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());

        //Step 4: 向消息服务发送供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(),order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 5: 订单内部流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.VALIDATE_GRADE_TWO, order.getVendorInnerStatus(), StringUtils.hasLength(agreeVO.getReason()) ? agreeVO.getReason() : "");

        return Wrapper.success();
    }

    /**
     * “待审核订单（一级）” - 批量提交审核
     * @param headers  Http头部信息
     * @param orderIds 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> batchValidateOrdersGradeTwo(HttpHeaders headers, List<OrderIdVO> orderIds) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        List<OrderDO> orders = orderRepository.findAllById(orderIds.stream().map(OrderIdVO::getOrderId).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(orders) || orderIds.size() != orders.size() || orders.stream().anyMatch(order -> !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId()))) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 记录每个订单的上一次内部状态，用于发送报表数据
        Map<Long, Integer> lastVendorInnerStatusMap = orders.stream().collect(Collectors.toMap(OrderDO::getId, OrderDO::getVendorInnerStatus));

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        for (OrderDO order : orders) {
            Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, OrderServiceContants.AGREE);
            if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
            }
        }

        orderRepository.saveAll(orders);

        orders.forEach(order -> {
            //Step 3: 向报表服务发送统计数据
            baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatusMap.getOrDefault(order.getId(), 0), order.getVendorInnerStatus());

            //Step 4: 向消息服务发送供应购商实时消息
            baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(),order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());

            //Step 5: 订单内、外流转记录
            baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.VALIDATE_GRADE_TWO, order.getVendorInnerStatus(), "");
        });

        return Wrapper.success();
    }

    /**
     * “待确认订单” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<OrderPageQueryVO>> pageToConfirmOrders(HttpHeaders headers, OrderValidatePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        List<Integer> vendorInnerStatuses = Stream.of(VendorInnerStatusEnum.VENDOR_SUBMIT_VALIDATE_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM.getCode()).collect(Collectors.toList());
        Page<OrderDO> pageList = baseOrderService.pageVendorOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), vendorInnerStatuses, null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            OrderPageQueryVO queryVO = new OrderPageQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待确认订单” - 查询订单详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorOrderDetailVO> getToConfirmOrderDetails(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return baseOrderService.getVendorOrderDetail(order, Stream.of(VendorInnerStatusEnum.VENDOR_SUBMIT_VALIDATE_NOT_PASSED, VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE_NOT_PASSED, VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO_NOT_PASSED, VendorInnerStatusEnum.VENDOR_TO_CONFIRM).collect(Collectors.toList()));
    }

    /**
     * “待确认订单” - 确认
     * @param headers Http头部信息
     * @param agreeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> confirmOrder(HttpHeaders headers, OrderAgreeVO agreeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        List<Integer> vendorInnerStatuses = Stream.of(VendorInnerStatusEnum.VENDOR_SUBMIT_VALIDATE_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_ONE_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_VALIDATE_GRADE_TWO_NOT_PASSED.getCode(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM.getCode()).collect(Collectors.toList());
        OrderDO order = orderRepository.findById(agreeVO.getOrderId()).orElse(null);
        if (order == null || !vendorInnerStatuses.contains(order.getVendorInnerStatus()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 参数判断
        if (agreeVO.getAgree().equals(OrderServiceContants.DISAGREE) && !StringUtils.hasLength(agreeVO.getReason())) {
            return Wrapper.fail(ResponseCode.ORDER_VALIDATE_REASON_CAN_NOT_BE_EMPTY);
        }

        //记录上一次的供应商状态，用于发送报表数据
        int lastVendorInnerStatus = order.getVendorInnerStatus();

        //Step 2: 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, agreeVO.getAgree());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        //Step 3 : 确认订单之后有可能是支付环节，判断是否跳过支付环节
        if (agreeVO.getAgree().equals(OrderServiceContants.AGREE)) {
            Wrapper<OrderPaymentBO> jumpResult = baseOrderPaymentService.jumpOverOrderPaySerialTasks(order);
            if (jumpResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(jumpResult.getCode(), jumpResult.getMessage());
            }
        }

        //Step 4: 如果是拼团订单，向营销服务发送拼团数据，等待拼团结果通知
        baseOrderService.notifyGroupOrder(order);

        //Step 4-2: 如果是代发货订单,向营销服务发送优惠券信息
        baseOrderService.sendCoupons(order);

        orderRepository.saveAndFlush(order);

        //Step 5: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), lastVendorInnerStatus, order.getVendorInnerStatus());
        baseOrderService.reportBuyerOrder(order.getBuyerMemberId(), order.getBuyerRoleId(), null, order.getBuyerInnerStatus());

        //Step 6: 向消息服务发送采购商、供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(),order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());
        baseOrderService.messageBuyerOrder(order.getBuyerMemberId(), order.getBuyerRoleId(),order.getBuyerUserId(), order.getBuyerInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 7: 订单内、外流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), agreeVO.getAgree().equals(OrderServiceContants.AGREE) ? OrderOperationEnum.ACCEPT : OrderOperationEnum.REFUSE, order.getVendorInnerStatus(), StringUtils.hasLength(agreeVO.getReason()) ? agreeVO.getReason() : "");
        baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), agreeVO.getAgree().equals(OrderServiceContants.AGREE) ? OrderOperationEnum.ACCEPT : OrderOperationEnum.REFUSE, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), "");

        return Wrapper.success();
    }

    /**
     * “待确认支付结果” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorConfirmPayQueryVO>> pageToConfirmPayOrders(HttpHeaders headers, OrderValidatePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());
        Specification<OrderDO> specification = (Specification<OrderDO>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("vendorMemberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("vendorRoleId").as(Long.class), loginUser.getMemberRoleId()));
            //不查询采购商未提交的订单
            list.add(criteriaBuilder.notEqual(root.get("vendorInnerStatus").as(Integer.class), VendorInnerStatusEnum.WAITING_FOR_BUYER_SUBMIT.getCode()));
            //包含资金归集模式为“会员直接到账”模式，且外部状态为“待确认支付结果”
            Join<OrderDO, OrderPaymentDO> paymentJoin = root.join("payments", JoinType.LEFT);
            list.add(criteriaBuilder.and(criteriaBuilder.equal(paymentJoin.get("fundMode").as(Integer.class), FundModeEnum.DIRECT_TO_ACCOUNT.getCode()), criteriaBuilder.equal(paymentJoin.get("outerStatus").as(Integer.class), OrderOuterStatusEnum.TO_CONFIRM_PAYMENT.getCode())));

            //订单编号
            if (StringUtils.hasLength(pageVO.getOrderNo())) {
                list.add(criteriaBuilder.like(root.get("orderNo").as(String.class), "%" + pageVO.getOrderNo().trim() + "%"));
            }

            //订单摘要
            if (StringUtils.hasLength(pageVO.getDigest())) {
                list.add(criteriaBuilder.like(root.get("digest").as(String.class), "%" + pageVO.getDigest().trim() + "%"));
            }

            //采购会员名称
            if (StringUtils.hasLength(pageVO.getMemberName())) {
                list.add(criteriaBuilder.like(root.get("buyerMemberName").as(String.class), "%" + pageVO.getMemberName().trim() + "%"));
            }

            //订单起始时间
            if (StringUtils.hasLength(pageVO.getStartDate())) {
                list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), LocalDateTime.parse(pageVO.getStartDate().concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            }

            //订单结束时间
            if (StringUtils.hasLength(pageVO.getEndDate())) {
                list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), LocalDateTime.parse(pageVO.getEndDate().concat(" 23:59:59"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            }

            //订单类型
            if (NumberUtil.notNullOrZero(pageVO.getOrderType())) {
                list.add(criteriaBuilder.equal(root.get("orderType").as(Integer.class), pageVO.getOrderType()));
            }

            //供应商内部状态：“待确认支付结果”
            list.add(criteriaBuilder.equal(root.get("vendorInnerStatus").as(Integer.class), VendorInnerStatusEnum.VENDOR_TO_CONFIRM_PAYMENT.getCode()));
            //外部状态：“待确认支付结果”
            list.add(criteriaBuilder.equal(root.get("outerStatus").as(Integer.class), OrderOuterStatusEnum.TO_CONFIRM_PAYMENT.getCode()));

            //去重
            query.distinct(true);

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Page<OrderDO> pageList = orderRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            VendorConfirmPayQueryVO queryVO = new VendorConfirmPayQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            //显示最小的未确认支付的批次
            queryVO.setBatchNo(CollectionUtils.isEmpty(order.getPayments()) ? 0 : order.getPayments().stream().filter(payment -> payment.getFundMode().equals(FundModeEnum.DIRECT_TO_ACCOUNT.getCode()) && payment.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_CONFIRM_PAYMENT.getCode()) && payment.getOuterStatus().equals(OrderOuterStatusEnum.TO_CONFIRM_PAYMENT.getCode())).map(OrderPaymentDO::getBatchNo).min(Comparator.comparingInt(Integer::intValue)).orElse(0));
            queryVO.setBatchCount(CollectionUtils.isEmpty(order.getPayments()) ? 0 : order.getPayments().size());
            queryVO.setPaidAmount(NumberUtil.formatAmount(order.getPaidAmount()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待确认支付结果” - 查询订单详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorOrderDetailVO> getToConfirmPayOrderDetails(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        if (!order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_CONFIRM_PAYMENT.getCode()) || !order.getOuterStatus().equals(OrderOuterStatusEnum.TO_CONFIRM_PAYMENT.getCode())) {
            return Wrapper.fail(ResponseCode.ORDER_STATUS_IS_NOT_MATCHED);
        }

        return baseOrderService.getVendorOrderDetail(order);
    }

    /**
     * “待确认支付结果” - 确认支付结果
     * @param headers      Http头部信息
     * @param confirmPayVO 接口参数
     * @return 确认结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> confirmOrderPayment(HttpHeaders headers, ConfirmPayVO confirmPayVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(confirmPayVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return confirmOrderPayment(order, confirmPayVO, loginUser);
    }

    /**
     * “待新增销售发货单” -查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorSellDeliveryPageVO>> pageSellDeliveryOrders(HttpHeaders headers, OrderSellDeliveryPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());
        Specification<OrderDO> specification = (root, query, builder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(builder.equal(root.get("vendorMemberId").as(Long.class), loginUser.getMemberId()));
            list.add(builder.equal(root.get("vendorRoleId").as(Long.class), loginUser.getMemberRoleId()));
            //不查询采购商未提交的订单
            list.add(builder.notEqual(root.get("vendorInnerStatus").as(Integer.class), VendorInnerStatusEnum.WAITING_FOR_BUYER_SUBMIT.getCode()));

            //订单编号
            if (StringUtils.hasLength(pageVO.getOrderNo())) {
                list.add(builder.like(root.get("orderNo").as(String.class), "%" + pageVO.getOrderNo().trim() + "%"));
            }

            //订单摘要
            if (StringUtils.hasLength(pageVO.getDigest())) {
                list.add(builder.like(root.get("digest").as(String.class), "%" + pageVO.getDigest().trim() + "%"));
            }

            //采购会员名称
            if (StringUtils.hasLength(pageVO.getMemberName())) {
                list.add(builder.like(root.get("buyerMemberName").as(String.class), "%" + pageVO.getMemberName().trim() + "%"));
            }

            //订单起始时间
            if (StringUtils.hasLength(pageVO.getStartDate())) {
                list.add(builder.greaterThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), LocalDateTime.parse(pageVO.getStartDate().concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            }

            //订单结束时间
            if (StringUtils.hasLength(pageVO.getEndDate())) {
                list.add(builder.lessThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), LocalDateTime.parse(pageVO.getEndDate().concat(" 23:59:59"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            }

            //订单类型
            if (NumberUtil.notNullOrZero(pageVO.getOrderType())) {
                list.add(builder.equal(root.get("orderType").as(Integer.class), pageVO.getOrderType()));
            }

            //外部状态：“待确认支付结果”
            list.add(builder.equal(root.get("outerStatus").as(Integer.class), OrderOuterStatusEnum.TO_DELIVER.getCode()));

            //去重
            query.distinct(true);

            Predicate[] p = new Predicate[list.size()];
            return builder.and(list.toArray(p));
        };

        Page<OrderDO> pageList = orderRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            VendorSellDeliveryPageVO queryVO = new VendorSellDeliveryPageVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setBatchNo(order.getDeliveries().size());
            //显示最后一次发货的发货单号
            queryVO.setDeliveryNo("");
            order.getDeliveries().stream().max(Comparator.comparingInt(OrderDeliveryDO::getBatchNo)).ifPresent(delivery -> queryVO.setDeliveryNo(delivery.getDeliveryNo()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待新增销售发货单” - 创建发货单
     * @param headers Http头部信息
     * @param orderVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> createSellDelivery(HttpHeaders headers, SellDeliveryOrderVO orderVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);

        OrderDO order = orderRepository.findById(orderVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order);
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        SellDeliveryGoodsDO deliveryDO = new SellDeliveryGoodsDO();
        deliveryDO.setDigest(orderVO.getDigest());
        deliveryDO.setCreateTime(LocalDateTime.parse(orderVO.getOrderTime(), OrderServiceContants.DEFAULT_TIME_FORMATTER));
        deliveryDO.setInventoryName(orderVO.getInventoryName());
        deliveryDO.setInventoryRole(orderVO.getInventoryRole());
        deliveryDO.setOrderId(orderVO.getOrderId());
        deliveryDO.setOrderNo(order.getOrderNo());
        deliveryDO.setBuyerMemberId(order.getBuyerMemberId());
        deliveryDO.setBuyerRoleId(order.getBuyerRoleId());
        deliveryDO.setBuyerMemberName(order.getBuyerMemberName());
        deliveryDO.setRemark(orderVO.getRemark());
        //没有该字段，设置默认值
        deliveryDO.setVendorMemberId(0L);
        deliveryDO.setVendorRoleId(0L);
        deliveryDO.setVendorMemberName("");
        //商品明细
        deliveryDO.setDetailList(orderVO.getDetailList().stream().map(detail -> {
            SellDeliveryGoodsDetailDO detailDO = new SellDeliveryGoodsDetailDO();
            detailDO.setProductId(detail.getProductId());
            detailDO.setName(detail.getName());
            detailDO.setCategory(detail.getCategory());
            detailDO.setBrand(detail.getBrand());
            detailDO.setUnit(detail.getUnit());
            detailDO.setOrderQuantity(detail.getOrderQuantity());
            detailDO.setPrice(detail.getPrice());
            detailDO.setDeliveryQuantity(detail.getDeliveryQuantity());
            detailDO.setAmount(detail.getAmount());
            detailDO.setWeight(detail.getWeight());
            detailDO.setDeliveryGoods(deliveryDO);
            return detailDO;
        }).collect(Collectors.toSet()));

        //保存发货单
        sellDeliveryGoodsRepository.save(deliveryDO);

        //保存订单，修改订单状态
        orderRepository.saveAndFlush(order);

        return Wrapper.success();
    }

    /**
     * “待新增销售发货单” - 查看详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorSellDeliveryDetailVO> getSellDeliveryDetail(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);

        SellDeliveryGoodsDO delivery = sellDeliveryGoodsRepository.findFirstByOrderId(idVO.getOrderId());
        VendorSellDeliveryDetailVO detailVO = new VendorSellDeliveryDetailVO();

        //发货单不存在取订单商品详情数据，有发货单则取发货单商品详情数据
        if (delivery == null) {
            //查询订单数据
            OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
            if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
                return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
            }

            detailVO.setInventoryName("");
            detailVO.setInventoryRole("");
            detailVO.setDigest("");
            detailVO.setCreateTime(LocalDateTime.now().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            detailVO.setRemark("");
            detailVO.setOrderNo(order.getOrderNo());
            detailVO.setOrderId(idVO.getOrderId());
            detailVO.setBuyerMemberId(order.getBuyerMemberId());
            detailVO.setBuyerRoleId(order.getBuyerRoleId());
            detailVO.setBuyerMemberName(order.getBuyerMemberName());
            //订单商品明细
            detailVO.setDetailList(order.getProducts().stream().map(detail -> {
                SellDeliveryGoodsDetailVO goodsDetailVO = new SellDeliveryGoodsDetailVO();
                goodsDetailVO.setId(detail.getId());
                goodsDetailVO.setProductId(detail.getProductId());
                goodsDetailVO.setName(detail.getName());
                goodsDetailVO.setCategory(detail.getCategory());
                goodsDetailVO.setBrand(detail.getBrand());
                goodsDetailVO.setUnit(detail.getUnit());
                goodsDetailVO.setOrderQuantity(detail.getQuantity());
                goodsDetailVO.setPrice(detail.getPrice());
                goodsDetailVO.setDeliveryQuantity(BigDecimal.ZERO);
                goodsDetailVO.setReceiveQuantity(BigDecimal.ZERO);
                goodsDetailVO.setAmount(detail.getAmount());
                goodsDetailVO.setWeight(detail.getWeight());
                return goodsDetailVO;
            }).collect(Collectors.toList()));
        } else {
            detailVO.setInventoryName(delivery.getInventoryName());
            detailVO.setInventoryRole(delivery.getInventoryRole());
            detailVO.setDigest(delivery.getDigest());
            detailVO.setCreateTime(delivery.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            detailVO.setRemark(delivery.getRemark());
            detailVO.setOrderNo(delivery.getOrderNo());
            detailVO.setOrderId(idVO.getOrderId());
            detailVO.setBuyerMemberId(delivery.getBuyerMemberId());
            detailVO.setBuyerRoleId(delivery.getBuyerRoleId());
            detailVO.setBuyerMemberName(delivery.getBuyerMemberName());
            //发货单商品明细
            detailVO.setDetailList(delivery.getDetailList().stream().map(detail -> {
                SellDeliveryGoodsDetailVO goodsDetailVO = new SellDeliveryGoodsDetailVO();
                goodsDetailVO.setId(detail.getId());
                goodsDetailVO.setProductId(detail.getProductId());
                goodsDetailVO.setName(detail.getName());
                goodsDetailVO.setCategory(detail.getCategory());
                goodsDetailVO.setBrand(detail.getBrand());
                goodsDetailVO.setUnit(detail.getUnit());
                goodsDetailVO.setOrderQuantity(detail.getOrderQuantity());
                goodsDetailVO.setPrice(detail.getPrice());
                goodsDetailVO.setDeliveryQuantity(detail.getDeliveryQuantity());
                goodsDetailVO.setAmount(detail.getAmount());
                goodsDetailVO.setWeight(detail.getWeight());
                return goodsDetailVO;
            }).collect(Collectors.toList()));
        }

        //订单收货人信息
        detailVO.setConsignee(baseOrderConsigneeService.getOrderConsignee(idVO.getOrderId()));

        return Wrapper.success(detailVO);
    }

    /**
     * “审核销售发货单” - 提交审核
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> validateToSellDeliveryOrder(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorInnerStatus().equals(VendorInnerStatusEnum.VENDOR_TO_VALIDATE_DELIVERY.getCode()) || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order);
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        orderRepository.saveAndFlush(order);

        return Wrapper.success();
    }

    /**
     * “待新增物流单” - 查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorLogisticsPageVO>> pageCreateLogistics(HttpHeaders headers, CreateLogisticsPageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());
        Specification<OrderDO> specification = (root, query, builder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(builder.equal(root.get("vendorMemberId").as(Long.class), loginUser.getMemberId()));
            list.add(builder.equal(root.get("vendorRoleId").as(Long.class), loginUser.getMemberRoleId()));
            //不查询采购商未提交的订单
            list.add(builder.notEqual(root.get("vendorInnerStatus").as(Integer.class), VendorInnerStatusEnum.WAITING_FOR_BUYER_SUBMIT.getCode()));

            //订单编号
            if (StringUtils.hasLength(pageVO.getOrderNo())) {
                list.add(builder.like(root.get("orderNo").as(String.class), "%" + pageVO.getOrderNo().trim() + "%"));
            }

            //订单摘要
            if (StringUtils.hasLength(pageVO.getDigest())) {
                list.add(builder.like(root.get("digest").as(String.class), "%" + pageVO.getDigest().trim() + "%"));
            }

            //采购会员名称
            if (StringUtils.hasLength(pageVO.getMemberName())) {
                list.add(builder.like(root.get("buyerMemberName").as(String.class), "%" + pageVO.getMemberName().trim() + "%"));
            }

            //订单起始时间
            if (StringUtils.hasLength(pageVO.getStartDate())) {
                list.add(builder.greaterThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), LocalDateTime.parse(pageVO.getStartDate().concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            }

            //订单结束时间
            if (StringUtils.hasLength(pageVO.getEndDate())) {
                list.add(builder.lessThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), LocalDateTime.parse(pageVO.getEndDate().concat(" 23:59:59"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            }

            //订单类型
            if (NumberUtil.notNullOrZero(pageVO.getOrderType())) {
                list.add(builder.equal(root.get("orderType").as(Integer.class), pageVO.getOrderType()));
            }

            //外部状态：“待确认支付结果”
            list.add(builder.equal(root.get("outerStatus").as(Integer.class), OrderOuterStatusEnum.TO_LOGISTICS.getCode()));

            //去重
            query.distinct(true);

            Predicate[] p = new Predicate[list.size()];
            return builder.and(list.toArray(p));
        };

        Page<OrderDO> pageList = orderRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            VendorLogisticsPageVO queryVO = new VendorLogisticsPageVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setBatchNo(order.getDeliveries().size());
            //显示最后一次发货的发货单号
            queryVO.setDeliveryNo("");
            order.getDeliveries().stream().max(Comparator.comparingInt(OrderDeliveryDO::getBatchNo)).ifPresent(delivery -> queryVO.setDeliveryNo(delivery.getDeliveryNo()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待新增物流单” - 查看详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorLogisticsDetailVO> getLogisticsDetail(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);

        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        VendorLogisticsDetailVO detailVO = new VendorLogisticsDetailVO();
        detailVO.setOrderId(order.getId());
        detailVO.setOrderNo(order.getOrderNo());
        //显示最后一次发货的发货单号
        detailVO.setDeliveryNo("");
        order.getDeliveries().stream().max(Comparator.comparingInt(OrderDeliveryDO::getBatchNo)).ifPresent(delivery -> detailVO.setDeliveryNo(delivery.getDeliveryNo()));
        //订单收货人信息
        detailVO.setConsignee(baseOrderConsigneeService.getOrderConsignee(idVO.getOrderId()));

        return Wrapper.success(detailVO);
    }

    /**
     * “新增物流单” - 选择商品 - 发货单商品明细
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorLogisticsProductQueryVO>> pageLogisticsProducts(HttpHeaders headers, VendorLogisticsProductPageVO pageVO) {
        baseCacheService.needLoginFromBusinessPlatform(headers);

        QSellDeliveryGoodsDO qDeliveryGoods = QSellDeliveryGoodsDO.sellDeliveryGoodsDO;
        QSellDeliveryGoodsDetailDO qDeliveryGoodsDetail = QSellDeliveryGoodsDetailDO.sellDeliveryGoodsDetailDO;

        JPAQuery<VendorLogisticsProductQueryVO> query = jpaQueryFactory.select(
                Projections.constructor(VendorLogisticsProductQueryVO.class,
                        qDeliveryGoodsDetail.productId,
                        qDeliveryGoodsDetail.name,
                        qDeliveryGoodsDetail.category,
                        qDeliveryGoodsDetail.brand,
                        qDeliveryGoodsDetail.unit,
                        qDeliveryGoodsDetail.deliveryQuantity,
                        qDeliveryGoodsDetail.weight))
                .from(qDeliveryGoods)
                .leftJoin(qDeliveryGoodsDetail).on(qDeliveryGoods.id.eq(qDeliveryGoodsDetail.deliveryGoods.id))
                .where(qDeliveryGoods.orderId.eq(pageVO.getOrderId()));

        //品类
        if (StrUtil.isNotBlank(pageVO.getCategory())) {
            query.where(qDeliveryGoodsDetail.category.like("%" + pageVO.getCategory().trim() + "%"));
        }

        //品牌
        if (StrUtil.isNotBlank(pageVO.getBrand())) {
            query.where(qDeliveryGoodsDetail.brand.like("%" + pageVO.getBrand().trim() + "%"));
        }

        //商品名称
        if (StrUtil.isNotBlank(pageVO.getName())) {
            query.where(qDeliveryGoodsDetail.name.like("%" + pageVO.getName().trim() + "%"));
        }

        //总数、排序、分页
        long totalCount = query.fetchCount();
        query.orderBy(qDeliveryGoodsDetail.id.asc());
        query.limit(pageVO.getPageSize()).offset(pageVO.getCurrentOffset());

        return Wrapper.success(new PageData<>(totalCount, query.fetch()));
    }

    /**
     * “待确认支付结果” - 确认支付结果
     * @param order        订单
     * @param confirmPayVO 接口参数
     * @param loginUser    登录用户
     * @return 确认结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> confirmOrderPayment(OrderDO order, ConfirmPayVO confirmPayVO, UserLoginCacheDTO loginUser) {
        //Step 1: 修改支付批次的状态
        Wrapper<Void> confirmResult = baseOrderPaymentService.vendorConfirmPayment(order, confirmPayVO.getBatchNo(), confirmPayVO.getAgree());
        if (confirmResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Wrapper.fail(confirmResult.getCode(), confirmResult.getMessage());
        }

        //Step 2: 如果是拼团订单，向营销服务发送拼团数据，等待拼团结果通知
        baseOrderService.notifyGroupOrder(order);

        //Step 2-1: 如果是代发货订单,向营销服务发送优惠券信息
        baseOrderService.sendCoupons(order);

        // 添加完成时间
        if(order.getOuterStatus().equals(OrderOuterStatusEnum.ACCOMPLISHED.getCode())){
            order.setFinishTime(LocalDateTime.now());
        }
        //Step 3: 保存订单状态
        orderRepository.saveAndFlush(order);

        //Step 4: 向报表服务发送统计数据
        baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM_DELIVERY, null);
        baseOrderService.reportBuyerOrder(order.getBuyerMemberId(), order.getBuyerRoleId(), null, BuyerInnerStatusEnum.BUYER_TO_RECEIVE);

        //Step 5: 向消息服务发送采购商、供应购商实时消息
        baseOrderService.messageVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(),order.getVendorUserId(), order.getVendorInnerStatus(), order.getOrderNo(), order.getDigest());
        baseOrderService.messageBuyerOrder(order.getBuyerMemberId(), order.getBuyerRoleId(),order.getBuyerUserId(), order.getBuyerInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 6: 订单内、外流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.CONFIRM_PAYMENT, order.getVendorInnerStatus(), "");
        baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), OrderOperationEnum.CONFIRM_PAYMENT, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), "");

        //Step 7: 订单完成后的操作
        baseOrderService.operateAfterOrderAccomplished(order);
        return Wrapper.success();
    }

    /**
     * “待确认发货订单” -查询订单列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorDeliveryQueryVO>> pageToDeliveryOrders(HttpHeaders headers, OrderValidatePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Page<OrderDO> pageList = baseOrderService.pageVendorOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM_DELIVERY.getCode(), null, pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            VendorDeliveryQueryVO queryVO = new VendorDeliveryQueryVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setBatchNo(order.getDeliveries().size());
            //显示最后一次发货的发货单号
            queryVO.setDeliveryNo("");
            order.getDeliveries().stream().max(Comparator.comparingInt(OrderDeliveryDO::getBatchNo)).ifPresent(delivery -> queryVO.setDeliveryNo(delivery.getDeliveryNo()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }


    /**
     * “待确认发货订单” - 查询订单详情
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<VendorOrderDetailVO> getToDeliveryOrderDetails(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        return baseOrderService.getVendorOrderDetail(order);
    }

    /**
     * “待确认发货订单” - “确认发货” - 查询商品列表
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<VendorDeliveryProductVO>> getToDeliveryProducts(HttpHeaders headers, VendorDeliveryNoAndOrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //检查订单发货条件
        Wrapper<TransferOrderDeliveryBO> deliveryCheckResult = baseOrderProductService.checkOrderDelivery(order, null);
        if (deliveryCheckResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(deliveryCheckResult.getCode(), deliveryCheckResult.getMessage());
        }

        return Wrapper.success(baseOrderProductService.listVendorDeliveryProducts(order));
    }

    /**
     * “待确认发货订单” - 发货
     * @param headers    Http头部信息
     * @param deliveryVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> deliveryOrder(HttpHeaders headers, VendorDeliveryVO deliveryVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(deliveryVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //Step 1: 检查订单发货条件
        Wrapper<TransferOrderDeliveryBO> deliveryCheckResult = baseOrderProductService.checkOrderDelivery(order, deliveryVO);
        if (deliveryCheckResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(deliveryCheckResult.getCode(), deliveryCheckResult.getMessage());
        }

        //Step 2: 当前订单发货
        Wrapper<Void> deliveryResult = deliveryOrder(loginUser, order, deliveryVO);
        if (deliveryResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(deliveryResult.getCode(), deliveryResult.getMessage());
        }

        //Step 3: 根据检查结果，判断是否要将转单前的订单发货
        return deliveryCheckResult.getData().getDeliverSeparatedOrder() ? deliveryOrder(loginUser, deliveryCheckResult.getData().getOrder(), deliveryCheckResult.getData().getDeliveryVO()) : Wrapper.success();
    }

    /**
     * “待确认发货订单” - 发货
     * @param loginUser  登录用户
     * @param order      发货订单
     * @param deliveryVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> deliveryOrder(UserLoginCacheDTO loginUser, OrderDO order, VendorDeliveryVO deliveryVO) {
        //Step 1 : 校验参数，保存发货记录
        Wrapper<OrderDeliveryBO> checkResult = baseOrderDeliveryService.checkVendorOrderDelivery(order, deliveryVO);
        if (checkResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Wrapper.fail(checkResult.getCode(), checkResult.getMessage());
        }

        // 如果没有发货商品，返回
        if (checkResult.getData().getNoDeliveryProducts()) {
            return Wrapper.success();
        }

        //Step 2 : 执行工作流任务（修改订单状态、记录内外流转记录）
        Wrapper<ProcessTaskBO> taskResult = baseOrderTaskService.execOrderProcess(order, checkResult.getData().getTaskJumpParameter());
        if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        orderRepository.saveAndFlush(order);

        //Step 3: 检查自动收货配置，将发货信息推送至消息队列，自动收货
        baseOrderScheduleService.scheduleOrderDelivery(order, checkResult.getData().getBatchNo());

        //Step 4: 如果全部发货完毕，供应商“待确认发货”统计数 -1
        //        如果是第一次发货，采购商“待确认收货”统计数 +1
        if (checkResult.getData().getDeliveryDone()) {
            baseOrderService.reportVendorOrder(order.getVendorMemberId(), order.getVendorRoleId(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM_DELIVERY, null);
        }

        if (checkResult.getData().getBatchNo() == 1) {
            baseOrderService.reportBuyerOrder(order.getBuyerMemberId(), order.getBuyerRoleId(), null, BuyerInnerStatusEnum.BUYER_TO_RECEIVE);
        }

        //Step 5: 向消息服务发送采购商实时消息
        baseOrderService.messageBuyerOrder(order.getBuyerMemberId(), order.getBuyerRoleId(),order.getBuyerUserId(), order.getBuyerInnerStatus(), order.getOrderNo(), order.getDigest());

        //Step 6: 订单内、外流转记录
        baseOrderHistoryService.saveVendorInnerHistory(loginUser.getMemberId(), loginUser.getMemberRoleId(), loginUser.getUserName(), loginUser.getUserOrgName(), loginUser.getUserJobTitle(), order.getId(), order.getOrderNo(), OrderOperationEnum.CONFIRM_DELIVERY, order.getVendorInnerStatus(), OrderStringEnum.DELIVERY_NUMBER.getName().concat(checkResult.getData().getDeliveryNo()));
        baseOrderHistoryService.saveVendorOrderOuterHistory(order.getId(), order.getOrderNo(), order.getVendorMemberId(), order.getVendorRoleId(), order.getVendorMemberName(), loginUser.getMemberRoleName(), OrderOperationEnum.CONFIRM_DELIVERY, order.getOuterStatus(), OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()), OrderStringEnum.DELIVERY_NUMBER.getName().concat(checkResult.getData().getDeliveryNo()));
        return Wrapper.success();
    }

    /**
     * 代客下单 - 创建订单
     * @param headers HttpHeader信息
     * @param orderVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> createAgentOrder(HttpHeaders headers, AgentOrderVO orderVO) {
        return orderCreationService.createAgentOrder(headers, orderVO);
    }

    /**
     * 代客下单 - 查询支付方式与支付渠道列表
     * @param headers   Http头部信息
     * @param payTypeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<OrderPayTypeDetailVO>> findAgentOrderPayTypes(HttpHeaders headers, AgentOrderPayTypeVO payTypeVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        return baseOrderProcessService.findMemberPayment(payTypeVO.getBuyerMemberId(), payTypeVO.getBuyerRoleId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
    }

    /**
     * 代客下单 - 根据企业商城类型获取下单模式和类型
     * @param headers    Http头部信息
     * @param shopTypeVO 订单来源商城的类型
     * @return 查询结果
     */
    @Override
    public Wrapper<OrderModeVO> findAgentOrderModeTypes(HttpHeaders headers, OrderShopTypeVO shopTypeVO) {
        switch (ShopTypeEnum.parseCode(shopTypeVO.getShopType())) {
            case ENTERPRISE:
                return Wrapper.success(new OrderModeVO(OrderModeEnum.BUYER));
            case CHANNEL:
                return Wrapper.success(new OrderModeVO(OrderModeEnum.CHANNEL_DIRECT_BUY));
            case CHANNEL_SELF:
                return Wrapper.success(new OrderModeVO(OrderModeEnum.CHANNEL_STOCK_BUY));
            default:
                return Wrapper.success(new OrderModeVO());
        }
    }

    /**
     * 代客下单 - 查询支付环节列表
     * @param headers Http头部信息
     * @param payVO   接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<BuyerOrderPayNodeDetailVO>> findAgentOrderProcessPayment(HttpHeaders headers, AgentOrderProcessPayVO payVO) {
        UserLoginCacheDTO userLoginDTO = baseCacheService.needLoginFromBusinessPlatform(headers);
        //Step 1: 跨境商品不能与其他商品一起下单
        List<Boolean> crossBorders = payVO.getProducts().stream().map(product -> !Objects.isNull(product.getCrossBorder()) && product.getCrossBorder()).distinct().collect(Collectors.toList());
        if(crossBorders.size() > 1) {
            return Wrapper.fail(ResponseCode.ORDER_PRODUCT_TRADE_PROCESS_IS_DIFFERENT);
        }

        //Step 2: 查询供应商交易流程规则
        Wrapper<OrderTradeProcessBO> tradeProcessResult = baseOrderProcessService.findVendorTradeProcess(userLoginDTO.getMemberId(), userLoginDTO.getMemberRoleId(), payVO.getShopId(), crossBorders.get(0) ? OrderTradeProcessTypeEnum.ORDER_COMMERCE_IMPORT : OrderTradeProcessTypeEnum.ORDER_TRADE, payVO.getProducts().stream().map(productIdVO -> new OrderProductBO(productIdVO.getProductId(), productIdVO.getSkuId())).collect(Collectors.toList()));
        if (tradeProcessResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(tradeProcessResult.getCode(), tradeProcessResult.getMessage());
        }

        //Step 3: 返回支付环节配置
        return Wrapper.success(tradeProcessResult.getData().getPayNodes().stream().filter(payNode -> payNode.getPayRate().compareTo(BigDecimal.ZERO) > 0).map(payNode -> {
            BuyerOrderPayNodeDetailVO detailVO = new BuyerOrderPayNodeDetailVO();
            detailVO.setBatchNo(payNode.getBatchNo());
            detailVO.setPayNode(payNode.getPayNode());
            detailVO.setOuterStatusName(OrderOuterStatusEnum.TO_PAY.getName());
            detailVO.setPayRate(NumberUtil.formatPayRate(payNode.getPayRate()));
            return detailVO;
        }).collect(Collectors.toList()));
    }

    /**
     * 订单查询 - 获取小程序二维码
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<String> createMiniAppCode(HttpHeaders headers, OrderIdVO idVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        OrderDO order = orderRepository.findById(idVO.getOrderId()).orElse(null);
        if (order == null || !order.getVendorMemberId().equals(loginUser.getMemberId()) || !order.getVendorRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.ORDER_DOES_NOT_EXIST);
        }

        //获取小程序配置参数，param：二维码参数，page: 跳转页面路径 pages/mycommodityDetails/index
        return baseOrderService.createMiniCode(order.getId().toString(), "");
    }

    /**
     * 订单分页查询 - 通用 - 所有订单类型下拉框列表
     * @return 查询结果
     */
    @Override
    public Wrapper<List<DropdownItem>> getAllOrderType() {
        return Wrapper.success(baseOrderService.listOrderTypes());
    }

    /**
     * “待确认回单订单” - 查询订单分页列表
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<VendorReceiptOrderPageVO>> pageToConfirmReceiptOrders(HttpHeaders headers, OrderValidatePageVO pageVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);
        Page<OrderDO> pageList = baseOrderService.pageVendorOrders(loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getOrderNo(), pageVO.getDigest(), pageVO.getMemberName(), pageVO.getStartDate(), pageVO.getEndDate(), pageVO.getOrderType(), VendorInnerStatusEnum.VENDOR_TO_CONFIRM_RECEIPT.getCode(), OrderOuterStatusEnum.TO_CONFIRM_RECEIPT.getCode(), pageVO.getCurrent(), pageVO.getPageSize());
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(order -> {
            VendorReceiptOrderPageVO queryVO = new VendorReceiptOrderPageVO();
            queryVO.setOrderId(order.getId());
            queryVO.setOrderNo(order.getOrderNo());
            queryVO.setCreateTime(order.getCreateTime().format(OrderServiceContants.DEFAULT_TIME_FORMATTER));
            queryVO.setDigest(order.getDigest());
            queryVO.setMemberName(order.getBuyerMemberName());
            queryVO.setAmount(NumberUtil.formatAmount(order.getTotalAmount()));
            queryVO.setBatchNo(order.getDeliveries().size());
            //显示最后一次发货的发货单号
            queryVO.setDeliveryNo("");
            order.getDeliveries().stream().max(Comparator.comparingInt(OrderDeliveryDO::getBatchNo)).ifPresent(delivery -> queryVO.setDeliveryNo(delivery.getDeliveryNo()));
            queryVO.setOrderType(order.getOrderType());
            queryVO.setOrderTypeName(OrderTypeEnum.getNameByCode(order.getOrderType()));
            queryVO.setInnerStatus(order.getVendorInnerStatus());
            queryVO.setInnerStatusName(VendorInnerStatusEnum.getNameByCode(order.getVendorInnerStatus()));
            queryVO.setOuterStatus(order.getOuterStatus());
            queryVO.setOuterStatusName(OrderOuterStatusEnum.getNameByCode(order.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “待确认回单订单” - 确认回单
     * @param headers Http头部信息
     * @param orderVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> confirmOrderReceipt(HttpHeaders headers, VendorBatchNoAndOrderIdVO orderVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromBusinessPlatform(headers);

        OrderDeliveryDO orderDeliveryDO = orderDeliveryRepository.findFirstByOrderIdAndBatchNo(orderVO.getOrderId(), orderVO.getBatchNo());
        if (orderDeliveryDO == null) {
            return Wrapper.fail(ResponseCode.ORDER_DELIVERY_DOES_NOT_EXIST);
        }
        orderDeliveryDO.setVendorInnerStatus(VendorInnerStatusEnum.VENDOR_RECEIPT_CONFIRMED.getCode());

        orderDeliveryRepository.saveAndFlush(orderDeliveryDO);
        return Wrapper.success();
    }
}
